import { log } from '../utils/logger.js';
import { getClientIP, formatIP } from '../utils/ipHelper.js';

/**
 * 请求日志中间件 - 记录所有HTTP请求
 */
export function requestLogger(req, res, next) {
  const startTime = Date.now();
  const ip = formatIP(getClientIP(req));
  
  // 记录请求
  log.info(`收到请求: ${req.method} ${req.originalUrl}`, {
    ip,
    userAgent: req.get('user-agent')
  });

  // 监听响应完成
  res.on('finish', () => {
    const duration = Date.now() - startTime;
    const statusCode = res.statusCode;
    
    // 根据状态码选择日志级别
    if (statusCode >= 500) {
      log.error(`请求完成: ${req.method} ${req.originalUrl} [${statusCode}] ${duration}ms`, {
        ip,
        statusCode,
        duration
      });
    } else if (statusCode >= 400) {
      log.warn(`请求完成: ${req.method} ${req.originalUrl} [${statusCode}] ${duration}ms`, {
        ip,
        statusCode,
        duration
      });
    } else {
      log.info(`请求完成: ${req.method} ${req.originalUrl} [${statusCode}] ${duration}ms`, {
        ip,
        statusCode,
        duration
      });
    }
  });

  next();
}

